import axios from "axios";

//js文件中导入router的方法
import router from "@/routers";
//导入token
import { useTokenStore } from "@/stores/token.js";
//组件库消息提示
//登录页路径
import { LOGIN_URL } from "@/config";

const http = axios.create({
  timeout: 1000 * 86400,
  withCredentials: true,
  baseURL: "/api-self",
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
});
// 请求拦截
http.interceptors.request.use(
  config => {
    const tokenStore = useTokenStore();
    //这里的if判断可能用不到
    if (config.url === "/users/register" || config.url === "/users/send") {
      console.log("请求路径为注册页，无需设置请求头");
      return config;
    } else {
      if (tokenStore.token) {
        config.headers.Authorization = tokenStore.token;
      } else {
        console.log("token为空");
        router.replace(LOGIN_URL);
        //ElMessage.warning('请先登录');
      }
      return config;
    }
  },
  err => {
    Promise.reject(err);
  }
);
// 响应拦截
http.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);
export default http;
